package com.xk._02算法篇._01sort.sort.cmp;

import com.xk._02算法篇._01sort.sort.Sort;
import com.xk.tools.Integers;

/**
 * @description: 插入排序优化 思路：二分搜索法
 * @author: xu
 * @date: 2022/10/1 23:08
 */
public class InsertionSort3<E extends Comparable<E>> extends Sort<E> {
    /**
     * 插入排序优化 思路：二分搜索法
     */
    private void insertionSort3(){
        for (int begin = 1; begin < array.length; begin++) {
            insert(begin, search(begin));
        }
    }

    /**
     * 将source位置的元素插入到dest位置
     * @param source
     * @param dest
     */
    private void insert(int source, int dest){
        E v = array[source];
        for (int i = source; i > dest; i--){
            array[i] = array[i-1];
        }
        array[dest] = v;
    }

    /**
     * 利用二分搜索法找到 index 位置元素的待插入位置
     * 已经排好序的区间范围[0, index)
     * @param index
     * @return
     */
    private int search(int index) {
        int begin = 0;
        int end = index;
        while (begin < end) {
            int mid = (begin + end) >> 1;
            if (cmp(index, mid) >= 0) {
                begin = mid + 1;
            } else {
                end = mid;
            }
        }
        return begin;
    }

    @Override
    protected void sort() {
        insertionSort3();
    }

    public static void main(String[] args) {
        Integer[] array = Integers.random(20, 1, 100);
        Integers.println(array);

        Sort<Integer> insertionSort3 = new InsertionSort3<>();
        insertionSort3.sort(array);
        Integers.println(array);
        System.out.println(insertionSort3);
    }
}
